package bysj.controller.basic;

import bysj.domain.File;
import bysj.service.FileService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import util.UploadHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.List;

@Slf4j
@WebServlet("/Upload")
public class UploadController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //保存路径
        String path = request.getServletContext().getRealPath("/");
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        try {
            List<FileItem> fileList = UploadHelper.getFileList(request,1000,1000,1000);
            for(FileItem item : fileList){
                //得到上传的文件名称，
                String filename = item.getName();
                if(filename==null || filename.trim().equals("")){
                    continue;
                }
                File file = new File(filename,path,null);
                int id = FileService.getInstance().addFile(file);
                UploadHelper.localUpload(fileList,filename,path);
                log.info(filename);
                message.put("message", "上传成功");
                response.getWriter().print(message);
            }
        } catch (FileUploadException | SQLException e) {
            e.printStackTrace();
        }
    }
}
